<?php namespace App\Services;

use Auth;
use App\Facades\Infra\OrderManager;
use App\Facades\Infra\CommodityManager;
use App\Exceptions\OrderException;
use DB;

class OrderService{

	public function addOrder($data){

		$userIntegration = Auth::user()->customerInfo->integration;

		$commodityConditions['id'] = $data['commodity_id'];

		$commodity = CommodityManager::getCommodities($commodityConditions);

		$totleIntegration = $commodity->c_integration*$data['commodity_number'];

		if($commodity->c_number <= 0 || $commodity->c_number < $data['commodity_number']){
			throw new OrderException('商品数量不足');
		}

		if($userIntegration < $totleIntegration){
			throw new OrderException();
		}

		$customerInfoData = [
			'integration' => $userIntegration-$totleIntegration
		];

		$commodityData = [
			'c_number' => $commodity->c_number-$data['commodity_number']
		];

		$orderData = [
			'c_name' => $commodity->c_name,
			'c_number' => $data['commodity_number'],
			'c_picture' => $commodity->c_picture,
			'c_integration' => $totleIntegration,
			'order_id' => time(),
			'address' => Auth::user()->collection->address,
			'phone' => Auth::user()->collection->phone,
			'collection_name' => Auth::user()->collection->name,
			'customer_id' => Auth::user()->id
		];

		DB::transaction(function() use($orderData,$customerInfoData,$commodityData,$data){
			CommodityManager::updateCommodity($data['commodity_id'],$commodityData);

			Auth::user()->customerInfo->update($customerInfoData);

			OrderManager::addOrder($orderData);
		});
	}

	public function updateStatus($data){
		$id = $data['id'];

		OrderManager::updateOrder($id,$data);
	}


	public function getOrdersByCustomer(){
		$conditions['customer_id'] = Auth::user()->id;

		return OrderManager::getOrders($conditions,true)->orderBy('created_at','desc')->get();
	}

	public function getOrders($conditions){
		return OrderManager::getOrders($conditions,true)->orderBy('created_at','desc')->paginate(10);
	}

	public function getOrder($data){
		$conditions = [
			'id' => $data['id']
		];

		return OrderManager::getOrders($conditions,false);
	}

	public function getOrderByCustomer($data){
		$conditions = [
			'id' => $data['id'],
			'customer_id' => Auth::user()->id
		];

		return OrderManager::getOrders($conditions,false);
	}

}